package com.example.common.update;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;

import java.util.Date;

/**
 * 李佳栋在 2017/11/20 创建
 * 邮箱: helloxiangsheng@163.com
 * 功能: 下载应用
 */

public class FileDownload {

    public static final int MAX_PROGRESS = 100;

    private Context mContext;
    private final long mDownloadId;
    private FileDownload.View mUpdateView;
    private final DownloadManager mDownloadManager;
    private final DownloadStateReceiver mDownloadStateReceiver;
    private final DownloadProgressChangeObserver mDownloadProgressChangeObserver;
    private final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");

    private FileDownload(Context context, FileDownload.Builder builder) {
        this.mContext = context;
        this.mUpdateView = builder.updateView;

        // 配置请求、注册广播
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(builder.url));
        mDownloadProgressChangeObserver = new DownloadProgressChangeObserver(null);
        mContext.getContentResolver().registerContentObserver(CONTENT_URI,
                true, mDownloadProgressChangeObserver);
        request.setAllowedOverRoaming(false);
        request.setMimeType("application/vnd.android.package-archive");

        // 不显示通知栏
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setVisibleInDownloadsUi(false);

        // 设置下载的路径
        request.setDestinationInExternalFilesDir(mContext, builder.dirType, builder.subPath);
        mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        mDownloadId = mDownloadManager.enqueue(request);
        mDownloadStateReceiver = new DownloadStateReceiver();
        mContext.registerReceiver(mDownloadStateReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    // 下载状态监听
    class DownloadStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(mDownloadId);
            Cursor c = mDownloadManager.query(query);

            if (c.moveToFirst()) {
                int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    mUpdateView.successful(mDownloadManager.getUriForDownloadedFile(mDownloadId));
                    clear();
                } else if (status == DownloadManager.STATUS_FAILED) {
                    mUpdateView.failed();
                    clear();
                }
            }

            c.close();
        }
    }

    // 下载进度监听
    class DownloadProgressChangeObserver extends ContentObserver {

        DownloadProgressChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(mDownloadId);
            DownloadManager dManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            final Cursor cursor = dManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                final int totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                final int currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                float progress = (cursor.getFloat(currentColumn) / cursor.getFloat(totalColumn)) * MAX_PROGRESS;
                mUpdateView.progress(progress);
            }
        }
    }

    // 清空引用
    private void clear() {
        mContext.unregisterReceiver(mDownloadStateReceiver);
        mContext.getContentResolver().unregisterContentObserver(mDownloadProgressChangeObserver);
        mContext = null;
    }

    static class Builder {
        private String subPath;
        private String dirType;
        private String url;
        private View updateView;

        public Builder setSubPath(String subPath) {
            this.subPath = subPath;
            return this;
        }

        public Builder setDirType(String dirType) {
            this.dirType = dirType;
            return this;
        }

        public Builder setUrl(String url) {
            this.url = url;
            return this;
        }

        public Builder setUpdateView(View updateView) {
            this.updateView = updateView;
            return this;
        }

        public FileDownload download(Context context) {
            return new FileDownload(context, this);
        }
    }

    public interface View {

        void successful(Uri uriForDownloadedFile);

        void failed();

        void progress(float progress);
    }
}
